package com.levy.contronller.jvm.classLoader;

import java.io.*;

/**
 * Created by levy on 2019/5/26.
 */
public class MyClassLoader extends ClassLoader {

    private String classLoaderName;

    private String path;

    public MyClassLoader(String classLoaderName) {
        // 将系统根加载器当作该类加载器的父类
        super();
        this.classLoaderName = classLoaderName;
    }

    public MyClassLoader(ClassLoader parent, String classLoaderName) {
        // 显示指定该类加载器的父加载器
        super(parent);
        this.classLoaderName = classLoaderName;
    }


    public MyClassLoader(ClassLoader parent){
        super(parent);
    }

    public void setPath(String path) {
        this.path = path;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        System.out.println("findClass invoked: " + name);
        System.out.println("class loader name: " + this.classLoaderName);

        byte[] bytes = this.loadClassData(name);
        return this.defineClass(name, bytes, 0, bytes.length);
    }


    private byte[] loadClassData(String className) {

        InputStream is = null;
        byte[] data = null;
        ByteArrayOutputStream baos = null;

        className = className.replace(".", "/");
        try {
            is = new FileInputStream(new File(this.path + className + ".class"));
            baos = new ByteArrayOutputStream();
            int ch;
            while (-1 != (ch = is.read())) {
                baos.write(ch);
            }
            data = baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }


    public static void main(String[] args) throws ClassNotFoundException, InterruptedException {
        MyClassLoader myloader1 = new MyClassLoader("myloader1");
        myloader1.setPath("D:\\Idea_workspace\\test\\target\\classes\\com\\levy\\contronller\\jvm\\classLoader");

        Class<?> clazz = myloader1.loadClass("com.levy.contronller.jvm.classLoader.MyTest1");
        System.out.println("class: " + clazz.hashCode());
        Object o = clazz.getInterfaces();
        System.out.println(o);

        System.out.println();

        myloader1 = null;
        clazz = null;
        o = null;

        System.gc();
        Thread.sleep(100000);


        myloader1 = new MyClassLoader("myloader1");
        myloader1.setPath("D:\\Idea_workspace\\test\\target\\classes\\com\\levy\\contronller\\jvm\\classLoader");


        clazz = myloader1.loadClass("com.levy.contronller.jvm.classLoader.myTest1");
        System.out.println("class: " + clazz.hashCode());
        o = clazz.getInterfaces();
        System.out.println(o);

        System.out.println();

    }


}
